<?php

class IndexController extends Model3_Controller
{
    
    public function indexAction()
    {
        
    }

    public function registerAction()
    {

        $this->view->getJsManager()->addJs('jquery/jquery.min.v1.4.2.js');
        $this->view->getJsManager()->addJs('jquery/jquery.validate.js');
        $this->view->getJsManager()->addJs('tiny_mce/tiny_mce.js');
        $this->view->getJsManager()->addJs('tiny_mce/tiny_mce_src.js');
        $this->view->getJsManager()->addJs('text.js');
        $this->view->getJsManager()->addJs('register/register.js');
        //$this->view->getJsManager()->addJs('sheepIt/jquery.sheepItPlugin-1.0.0.min.js');
        //$this->view->getJsManager()->addJs('register/documents.js');
        $this->view->getJsManager()->addJs('jquery/jquery-ui-1.8.12.custom.min.js');
        //$this->view->getJsManager()->addJs('register/autocomplete.js');

        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        /* @var $em Doctrine\ORM\EntityManager */

        $this->view->countries = $em->getRepository('DefaultDb_Entities_Countries')->getAllCountry();
        $this->view->res = true;

        $validator = new Model3_Validator_Form();
        $ids = array("email", "pass", "firstName", "lastName", "country");
        $datos = array("Email", "Password", "First Name", "Last Name", "Country");
        foreach ($ids as $i => $id)
        {
            $validator->addValidation($id, Model3_Validator_Form::REQUIRED, null, 'The ' . $datos[$i] . ' El campo es obligatorio');
        }
        $validator->addValidation('pass', Model3_Validator_Form::MINLENGTH, 6, 'La contrase&ntilde;a debe tener minimo 6 digitos');
        if ($this->getRequest()->isPost())
        {
            if ($validator->validateForm())
            {
                $post = $this->getRequest()->getPost();
                /* @var $user DefaultDb_Entities_User */
                $user = new DefaultDb_Entities_User();
                $city = $em->getRepository('DefaultDb_Entities_Countries')->find($post['country']);
                $dbs = Model3_Registry::getInstance()->get('databases');
                $em = $dbs['DefaultDb'];

                if ($post['pass'] == $post['confirmation'])
                {
                    $user->setUsername($post['email']);
                    $user->setPassword(md5($post['pass']));
                    $user->setFirstName($post['firstName'], ENT_QUOTES, "UTF-8");
                    $user->setLastName($post['lastName']);
                    $user->setCity($city);
                    $user->setConfirmPassword($post['confirmation']);
                    $user->setTypeLoginUser(DefaultDb_Entities_User::USER_COMMON);
                    $user->setTypeLoginUser(2);
                    $date = new DateTime;
                    $em->persist($user);
                    $em->flush();
                    $mailHelper = new Helper_MailHelper();
                     //$mailHelper->sendMailWelcome($user->getUsername(), $user, $date);
                    ////var_dump($user);
                    $this->redirect('Index/index/register/success');
                }
                else
                {
                    $this->view->res = false;
                    $this->view->errors = array("'La confirmacion del password es incorrecto'");
                }
            }
            else
            {
                $this->view->res = false;
                $this->view->errors = $validator->getErrors();
            }
        }
    }

    public function loginAction()
    {
        $validator = new Model3_Validator_Form();

        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            $auth = new Model3_Auth();

            if ($auth->authenticate($post['user'], md5($post['pass'])))
            {
                $credentials = Model3_Auth::getCredentials();
                switch ($credentials['type'])
                {
                    case 1 : $this->redirect('Dashboard/index');
                        break;
                    case 2 : $this->redirect('Index/index');
                        break;
                }
            }
            else
            {
                $this->view->res = false;
                //$this->view->errors = array("E-mail es incorrecto");
                $this->redirect('Index/index');
            }
        }
    }

    public function logoutAction()
    {
        Model3_Auth::deleteCredentials();
        $this->redirect();
    }

    public function recoverPassAction()
    {
        
    }

    public function sendPassAction()
    {
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            $dbs = Model3_Registry::getInstance()->get('databases');
            $em = $dbs['DefaultDb'];
            /* @var $userSearch DefaultDb_Entities_User */
            $userSearch = $em->getRepository('DefaultDb_Entities_User')->searchUserByEmail($post['email']);
            //var_dump($userSearch->getId());
            if ($userSearch)
            {
                $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
                $newPass = "";
                for ($i = 0; $i < 8; $i++)
                    $newPass .= substr($str, rand(0, 62), 1);
                //echo $newPass;
                //echo $userSearch->getId();
                $userSearch->setPassword(md5($newPass));
                $em->persist($userSearch);
                $em->flush();
                $helperMail = new Helper_MailHelper();
                $helperMail->sendPassword($post['email'], $newPass);
            }
            else
            {
                $this->view->res = false;
                $this->view->errors = array('This email not exist');
            }
        }
    }

    public function AxValidateEmailAction()
    {
        $this->view->setUseTemplate(false);
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            $dbs = Model3_Registry::getInstance()->get('databases');
            $em = $dbs['DefaultDb'];

            /* @var $userSearch DefaultDb_Entities_User */
            $user = $em->getRepository('DefaultDb_Entities_User')->searchUserByEmail($post['email']);
            if ($user && $user->getTypeLoginUser() == 3)
                $this->view->res = true;
        }
    }


    public function contactUsAction()
    {
        $this->view->getJsManager()->addJs('jquery/jquery.validate.js');
//        $this->view->getJsManager()->addJs('contactUs/contactUs.js');

//        $dbs = Model3_Registry::getInstance()->get('databases');
//        $em = $dbs['DefaultDb'];
//        $event = new DefaultDb_Entities_Contacts();
////        $admin = array('hector.benitez.fletes@gmail.com', 'cortestavo@gmail.com');
//        $admin = array('ayde.rod@gmail.com');
//
        if ($this->getRequest()->isPost())
        {
//            $post = $this->getRequest()->getPost();
//            $event->setFirstName($post['firstName']);
//            $event->setLastName($post['lastName']);
//            $event->setUsername($post['username']);
//            $event->setPnone($post['telephone']);
//            $event->setEventName($post['eventName']);
//            $event->setEventWebsite($post['eventWebsite']);
//            $event->setComments($post['comments']);
//
//            $date = new DateTime();
//            $mailHelper = new Helper_MailHelper();
//            foreach ($admin as $adm)
//                $mailHelper->sendMailBusinessComercial($adm, $event, $post['comments'], $date);
//
//            $em->persist($event);
//            $em->flush();
            $this->view->message = "El formulario de contacto se  ah enviado correctamente";
        }
    }


    public function galleryAction()
    {   
        $this->view->getJsManager()->addJs('jquery/jquery.min.v1.4.2.js');
        $this->view->getJsManager()->addJs('jquery/jquery.js');
        $this->view->getJsManager()->addJs('jquery/jquery.min.js');
        $this->view->getJsManager()->addJs('jquery/jquery-ui-1.8.12.custom.min.js');
        $this->view->getJsManager()->addJs('jquery/bootstrap.js');
        $this->view->getCssManager()->addCss('bootstrap/bootstrap.css');
        $this->view->getJsManager()->addJs('gallery/carousel.js');
    }

    public function directionAction()
    {
        
        
    }
    
    public function selectEventsAction()
    {
        $this->view->nameEvent = $this->getRequest()->getParam('events');
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $eventSearch = $em->getRepository('DefaultDb_Entities_Event')->searchEvent($this->view->nameEvent);
        $this->view->events = $eventSearch;
    }


    public function get_files($images_dir, $exts = array('jpg'))
    {
        // var_dump($images_dir);
        $files = array();
        $i = 0;
        if (is_dir($images_dir))
        {
            //  $images_dir = 'data/images/event_2';
            $handle = opendir($images_dir);
            //var_dump($handle);
            if ($handle)
            {
                while (false !== ($file = readdir($handle)))
                {

                    $extension = strtolower($this->get_file_extension($file));
                    if ($extension && in_array($extension, $exts))
                    {
                        $files[$i] = $file;
                        $i++;
                    }
                }
            }
            closedir($handle);
            return($files);
        }
        else
            return false;

//       var_dump($files);
    }

    public function get_file_extension($file_name)
    {
        return substr(strrchr($file_name, '.'), 1);
    }

    public function autocompleteAction()
    {
        $this->view->setUseTemplate(false);
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $company = array();

        $companies = $em->getRepository('DefaultDb_Entities_User')->findAllCompany();
        for ($i = 0; $i < count($companies); $i++)
        {
            $company[$i] = htmlentities($companies[$i]['company'] . '', ENT_QUOTES, 'ISO-8859-15');
            //$company[$i] = $companies[$i]['company'].'';  
        }
        $this->view->companies = $company;
    }

}
